package org.assistant.csp.utils;

import java.util.ArrayList;
import java.util.List;

public class TreeNode<T> {
	private long id;// 结点ID
	private int level;// 结点的级别，最高级为1级
	private long parentId;// 父结点ID
	private T nodeData;// 数据结点
	private List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();// parentId下的所有子结点

	public TreeNode(long id, long parentId, int level) {
		this.id = id;
		this.parentId = parentId;
		this.level = level;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public T getNodeData() {
		return nodeData;
	}

	public void setNodeData(T nodeData) {
		this.nodeData = nodeData;
	}

	public boolean haveChildren() {
		if (children.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	public boolean addChild(TreeNode<T> child) {
		return children.add(child);
	}

	public TreeNode<T> removeChild(int index) {
		return children.remove(index);
	}

	public TreeNode<T> getChild(int index) {
		return children.get(index);
	}

	public int childrenSize() {
		return children.size();
	}

	/**
	 * 根据指定的ID在该结点的所有子结点（及子结点的子结点）中获取TreeNode <br>
	 * 如果找不到，则返回null.
	 * 
	 * @param id
	 * @return
	 */
	public TreeNode<T> getChildById(long id) {
		if (id == this.getId()) {
			return this;
		}
		for (int i = 0; i < children.size(); i++) {
			TreeNode<T> child = children.get(i);
			if (id == child.getId()) {
				return child;
			} else {
				TreeNode<T> subChild = child.getChildById(id);
				if (subChild != null) {
					return subChild;
				}
			}
		}
		return null;
	}

	public long getParentId() {
		return parentId;
	}

	public void setParentId(long parentId) {
		this.parentId = parentId;
	}
}
